package com.hgw.springsecurityjwtdemo02.service.impl;

import com.hgw.springsecurityjwtdemo02.common.ResponseResult;
import com.hgw.springsecurityjwtdemo02.domian.LoginUser;
import com.hgw.springsecurityjwtdemo02.domian.User;
import com.hgw.springsecurityjwtdemo02.service.AuthService;
import com.hgw.springsecurityjwtdemo02.utils.JwtUtil;
import com.hgw.springsecurityjwtdemo02.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

/**
 * Description: 认证模块
 * Data time:2022/9/1 14:53
 * Author:TQ-3038-HuangGongWei
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    /**
     * 用户登陆
     * @param user
     * @return
     */
    @Override
    public ResponseResult login(User user) {
        // 1. 进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        if (Objects.isNull(authenticate)) {
            // 2. 如果认证没通过，给出对应的提示
            throw new RuntimeException("登陆失败");
        }
        // 3. 如果认证通过了，使用 userId 生成一个 jwt，jwt 存入 返回体 返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        HashMap<String, String> authToken = new HashMap<>();
        authToken.put("auth",jwt);
        // 4. 以 userId 为key,用户信息为 value 放入缓存
        redisCache.setCacheObject("token:"+userId, loginUser);

        return new ResponseResult(200,"登陆成功", authToken);
    }

    /**
     * 注销登陆
     * @return
     */
    @Override
    public ResponseResult logout() {
        // 获取 SecurityContextHolder 中的用户 id
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        // 删除 redis 中的值
        redisCache.deleteObject("token:"+userId);
        return new ResponseResult(200, "注销成功");
    }
}
